<?php
namespace control;
/*
*人才库
*/

class talentPoolClass extends adIndexClass
{
    private const page = 'talentPool';
    private const table = 'talent_pool';
    private const title = '人才库';
    public const px = 37.795275590551;//1cm转为像素
    public array $stateOption = ['草稿', '审核中', '已通过'];
    public array $marryOption = ['未婚', '已婚', '离异'];
    public array $residenceTypeOption = ['农业户口', '非农户口'];
    public array $opinionOption = ['予以录用', '进一步考察', '不予考虑'];

    /*列表-查询条件*/
    public function home()
    {

        $force = staffProfilesClass::forceDel();
        $html = '';
        if ($force){
            $html=checkbox(['name'=>'force','value'=>['1'=>'查看全部'],'checked'=>[]]).space;
        }
        //生成查询表单
        $html .=
            text(array("name" => "name", "title" => L('staffProfiles.table.name'))) .
            select(array("name" => "sex", "title" => L('staffProfiles.table.sex'), "option" => ['男', '女'])) .
            text(array("name" => "tel", "title" => L('staffProfiles.table.tel'))) .
            text(array("name" => "age", "title" => L('staffProfiles.table.age'))) .
            select(array("name" => "nation", "title" => L('staffProfiles.table.nation'), "option" => explode('、', para('nationOption')))) .
            repeatSelect(array('name' => 'hometown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province')) .
            selectMultiple(array("name" => "jobId", "title" => L('staffProfiles.table.appliedJob'), "table" => "job", 'sqlField' => 'name', 'sqlId' => 'id')) .
            text(array("name" => "registerDate",'class'=>'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('staffProfiles.table.registerDate')."-".L('staffProfiles.table.registerDate'))) .
            select(array("name" => "state", "title" => L('staffProfiles.table.stateText'), "option" => explode('，', para('talentPoolState'))));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//姓名
            "tel" => $this->post('tel'),//手机号
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "sex" => $this->post('sex'),//性别
            "nation" => $this->post('nation'),//民族
            "homeTown" => $this->post('homeTown'),//籍贯
            "jobId" => $this->post('jobId'),//应聘岗位
        );
        $and = " and workFlow !=2";
        if ($this->post('force')){
            $and = "";
        }
        if ($this->post('registerDate')) {
            $timeArr = explode(' ~ ', $this->post('registerDate'));
            $and .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }
        if ($this->post('age')) {
            $and .= " and (DATE_FORMAT(now(),'%Y')-date_format(birthDay,'%Y')) = '{$this->post('age')}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" =>"time desc,id"));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('staffProfiles.table.name'), L('staffProfiles.table.sex'), L('staffProfiles.table.tel'), L('staffProfiles.table.birthDay'), L('staffProfiles.table.age'), L('staffProfiles.table.nation'), L('staffProfiles.table.homeTown'), L('staffProfiles.table.appliedJob'), "登记日期", L('staffProfiles.table.stateText'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $staffObj = new staffProfilesClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => L('staffProfiles.button.edit'), "click" => "newIframe('" . L('staffProfiles.table.talentInfo') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => L('staffProfiles.table.talentInfo'), "click" => "newIframe('".L('staffProfiles.table.talentInfo')."','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $quitStaff = query('staff', " talentId = '$array[id]' and state = '离职'");
            if ($array['workFlow'] != 0 && !$quitStaff['stid']) {
                unset($dominate['edit']);
            }
            $job = query('job', " id = '$array[jobId]'");
            $tr[] = array($this->dominate($dominate), $array['name'], $array['sex'], $array['tel'], $array['birthDay'], $staffObj->age($array['birthDay']), $array['nation'], $array['homeTown'], $job['name'], self::formatDate($array['time']), $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('".L('staffProfiles.table.talentInfo')."','" . $url . "&fun=edit')\" class='spanButton'>".L('staffProfiles.button.addNew')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('staffProfiles.button.del')."</span>\n";
        }
        if ($this->power(self::page, "import")) {
            $button .= importTemplateClass::importTemplateButton(self::page) .
                $this->upButton(array("title" => L('staffProfiles.button.import'), "fun" => "import"));
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>".L('staffProfiles.button.export')."</span></a>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','downloadQrCode',{})\" class='spanButton'>".L('staffProfiles.button.downLoadQr')."</span>\n";
            $option = explode('，', para('talentPoolState'));
            $li = '';
            if (is_array($option)) {
                foreach ($option as $v) {
                    $li .= "<li>$v</li>";
                }
            }
            $button .= "<span class='spanButton'><span onclick=\"showState()\">".L('staffProfiles.button.settingState')."</span><div class='stateBlock' ><ul>{$li}</ul></div></span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        $json['html'] .= <<<for
<script>
$(".stateBlock li").click(function (){
    let state = $(this).text();
    showState();
    subForm('listForm',root+'control/adIndex.html?cla=talentPool&fun=setWorkFlow&state='+state)
});
</script>
for;
        return json_encode($json, 320);
    }



    /**
     * 下载二维码
     */
    public function downloadQrCode()
    {
        // 二维码
        $url = urlencode($this->root.'control/mTalentPool.html');
        $html = $this->generateQr($url, L('staffProfiles.talentPool.wechatR'));
        //返回
        return $this->layer(array("title" => L('staffProfiles.button.downLoadQr'), "height" => 500, 'width' => 900, "html" => $html));
    }

    /**
     * 生成二维码
     * @param $url
     * @param $text
     * @param string $type
     * @param string $para
     * @return string
     */
    public function generateQr($url, $text, $type = '二维码', $para = ''): string
    {

        if ($type == '小程序码') {
            $src = visitorClass::wxQRcode($url, $para);
        } else {
            $src = root . 'pay/wxpay/wxScanPng.php?url=' . $url;
        }
        $sizeOption = [
            [
                'name' => '2cm',
                'value' => '2',
            ],
            [
                'name' => '8cm',
                'value' => '8',
            ],
            [
                'name' => '32cm',
                'value' => '32',
            ]
        ];
        $li = '';
        foreach ($sizeOption as $k => $array) {
            $checked = $k == 0 ? 'checked' : '';
            $px = round(self::px * $array['value']);
            $li .= <<<ee
<li><label class="radioLabel">&nbsp;<input name="size" type="radio" value="{$array['value']}" $checked>&nbsp;{$array['name']}（{$px}px*{$px}px）</label></li>
ee;
        }
        $size = L('staffProfiles.talentPool.size');
        //生成表单
        return <<<efo
<div class="qr-content">
  <div class="left-content">
        <img alt="二维码" style="width: 300px;height: 300px" src="{$src}">
        <div>{$text}</div>
        <input id="url" type="hidden" value="$url">
         <input id="codeType" type="hidden" value="$type">
          <input id="para" type="hidden" value="$para">
  </div>
  <div class="right-content">
      <div class="right-content-top">
          <div class="right-content-top-title">$size</div>
          <div>
               <ul>
                    {$li}
               </ul>
          </div>
      </div>
      <input type="button" style="margin-top: 10px" onclick="downloadIamge()" class="searchSub" value="下载">
</div>
</div>
<style>
 .qr-content{width:800px;margin: 10px auto}
  .left-content{width: 350px;height: 350px;display: inline-block;border: 1px solid #e6e6e6;text-align: center;}
  .left-content img{margin-top: 30px}
  .right-content{width: 350px;height: 350px;display: inline-block;margin-left: 20px;vertical-align: top;}
  .right-content-top{width: 100%;border: 1px solid #e6e6e6;}
  .right-content-top-title{height: 35px;padding-left: 10px;line-height: 35px;border-bottom: 1px solid #e6e6e6}
  .right-content ul li{margin: 10px 5px}
</style>
<script>
function downloadIamge(){
    let width = $("input[name='size']:checked").val();
    let url = $("#url").val();
     let codeType = $("#codeType").val();
      let para = $("#para").val();
    
    window.open(root+'control/adIndex.html?cla=talentPool&fun=downloadQr&width='+width+'&para='+para+'&codeType='+codeType+'&url='+url)
}
</script>
efo;
    }

    /**
     * 下载
     */
    public function downloadQr()
    {
        $width = $this->get('width');
        $url = $this->get('url');
        $codeType = $this->get('codeType');
        $para = $this->get('para');
        if (empty($width) || !is_numeric($width)) {
            $json['warn'] = L('staffProfiles.talentPool.sizeWarn');
        } else {
            $width = round(self::px * $width);//cm转为px
            if ($codeType == '小程序码') {
                $src = visitorClass::wxQRcode($url, $para);
            } else {
                $src = root . 'pay/wxpay/wxScanPng.php?url=' . $url;
            }
            $path = 'img/qrCode';
            $this->_mkdir($path);
            $path = serverRoot . $path . '/qrCode.png';
            $bool = $this->resize_image($src, $path, $width, $width);
            if ($bool) {
                $this->downloadFile('二维码', $path);
                $json['warn'] = 2;
            } else {
                $json['warn'] = L('staffProfiles.talentPool.downloadFailed');
            }
        }
        echo $json['warn'];
    }


    /**
     * 改变图片的宽高
     *
     * @param string $img_src 原图片的存放地址或url
     * @param string $new_img_path 新图片的存放地址
     * @param int $new_width 新图片的宽度
     * @param int $new_height 新图片的高度
     * @return bool  成功true, 失败false
     * @author flynetcn (2009-12-16)
     *
     */
    public function resize_image($img_src, $new_img_path, $new_width, $new_height): bool
    {
        $img_info = @getimagesize($img_src);
        if (!$img_info || $new_width < 1 || $new_height < 1 || empty($new_img_path)) {
            return false;
        }
        if (str_contains($img_info['mime'], 'jpeg')) {
            $pic_obj = imagecreatefromjpeg($img_src);
        } elseif (str_contains($img_info['mime'], 'gif')) {
            $pic_obj = imagecreatefromgif($img_src);
        } elseif (str_contains($img_info['mime'], 'png')) {
            $pic_obj = imagecreatefrompng($img_src);
        } else {
            return false;
        }
        $pic_width = imagesx($pic_obj);
        $pic_height = imagesy($pic_obj);
        if (function_exists("imagecopyresampled")) {
            $new_img = imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($new_img, $pic_obj, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
        } else {
            $new_img = imagecreate($new_width, $new_height);
            imagecopyresized($new_img, $pic_obj, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
        }
        if (preg_match('~.([^.]+)$~', $new_img_path, $match)) {
            $new_type = strtolower($match[1]);
            switch ($new_type) {
                case 'jpg':
                    imagejpeg($new_img, $new_img_path);
                    break;
                case 'gif':
                    imagegif($new_img, $new_img_path);
                    break;
                case 'png':
                    imagepng($new_img, $new_img_path);
                    break;
                default:
                    imagejpeg($new_img, $new_img_path);
            }
        } else {
            imagejpeg($new_img, $new_img_path);
        }
        imagedestroy($pic_obj);
        imagedestroy($new_img);
        return true;

    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        } else {
            $title = ['*'.L('staffProfiles.table.name'), '*'.L('staffProfiles.table.sex'), '*'.L('staffProfiles.table.tel'), '*'.L('staffProfiles.talentPool.jobCode'),L('staffProfiles.talentPool.jobName'), L('staffProfiles.table.education'), L('staffProfiles.table.email'),L('staffProfiles.table.expect_address'),L('staffProfiles.table.expect_salary'),L('staffProfiles.table.idCard'),L('staffProfiles.table.birthDay').'('.L('staffProfiles.talentPool.date').')',L('staffProfiles.table.nation'),L('staffProfiles.table.homeTown'),'身高(cm)','体重(kg)','专业',L('staffProfiles.table.college'),L('staffProfiles.table.workInDate'),L('staffProfiles.table.health'),L('staffProfiles.table.marriage'),L('staffProfiles.table.politicsStatus'),L('staffProfiles.table.residenceAddress'),
                L('staffProfiles.table.liveAddress'),L('staffProfiles.table.postCode'),L('staffProfiles.table.secContactName'),L('staffProfiles.table.secContactRelation'),L('staffProfiles.table.secContactTel'),L('staffProfiles.talentPool.agreement'),L('staffProfiles.table.text')];
            $data[] = [
                '张三(示例数据)', '男', '13000000000',  'J0001', '总经理','本科','123@mail.com','重庆市','5000-8000','55142319880304500X', '1995-01-01','汉族','重庆市','170','60','计算机','重庆大学','2012-01-01','良好','未婚','群众','重庆市','重庆市','400000',
                '张五','兄弟','13111111111','','',''
            ];
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('staffProfiles.talentPool.downloadModel'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('staffProfiles.talentPool.importTemplate'). '.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /*数据导入分析*/
    public function import()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('staffProfiles.talentPool.edit_permission');
        } else {

            $data = $this->importHead(format:[
                2=>\Vtiful\Kernel\Excel::TYPE_STRING,
                9=>\Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $x = 0;
            $text = '';
            $education =  para('education','，');
            $nationOption = para('nationOption','、');
            $healthOption = para('healthOption','，');
            $jobTitleOption = para('jobTitleOption','，');
            $politicsStatus = para('politicsStatus','，');
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $cell[10] = self::importDateFormat($cell[10]);
                    $job = query('job', " orderNo = '$cell[3]'");//应聘岗位
                    $field = [
                        "id" => self::getId(),
                        'state' => '人才登记',
                        'workFlow' => 0,
                        'name' => $cell[0],
                        'sex' => $cell[1],
                        'tel' => $cell[2],
                        'jobId' => $job['id'],
                        'education' => $cell[5],
                        'email' => $cell[6],
                        'exWorkPlace' => $cell[7],
                        'exSalary' => $cell[8],
                        'idCard' => $cell[9],
                        'birthDay' => $cell[10],
                        'nation' => $cell[11],
                        'homeTown' => $cell[12],
                        'height' => $cell[13],
                        'weight' => $cell[14],
                        'major' => $cell[15],
                        'college' => $cell[16],
                        'workDate' => $cell[17],
                        'health' => $cell[18],
                        'marriage' => $cell[19],
                        'politicsStatus' => $cell[20],
                        'residenceAddress' => $cell[21],
                        'residenceType' => $cell[22],
                        'liveAddress' => $cell[23],
                        'postCode' => $cell[24],
                        'secContactName' => $cell[25],
                        'secContactRelation' => $cell[26],
                        'secContactTel' => $cell[27],
                        'text' => $cell[28],
                    ];
                    $annotation = [
                        'name' => L('staffProfiles.table.name'),
                        'sex' => L('staffProfiles.table.sex'),
                        'tel' => L('staffProfiles.table.tel'),
                        'jobId' => L('staffProfiles.table.appliedJob'),
                    ];
                    $rules = [
                        'name' => 'required',
                        'sex' => 'required',
                        'tel' => 'required|tel',
                        'jobId' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    $line = str_replace(['{{i}}'], [$i], L('job.other.line'));
                    $staffObj = new staffProfilesClass();
                    if ($result === false) {
                        $text .= $line."：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif (!empty($field['idCard']) && (static::total(array('sql' => "SELECT count(*) AS total FROM " . self::table . " where idCard = '{$field['idCard']}' and id !='$field[id]'")))) {
                        $text .= $line."：".L('staffProfiles.other.idCard_repeat_warn')."<br>";
                    } elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
                        $text .= $line."：".L('staffProfiles.tip.name_warn')."<br>";
                    } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
                        $text .= $line."：".L('staffProfiles.tip.email_warn')."<br>";
                    } elseif (!empty($field['birthDay']) && strtotime($field['birthDay']) === false) {
                        $text .= $line."：".L('staffProfiles.other.birthDayError')."<br>";
                    } elseif(!empty($field['birthDay']) && $staffObj->age($field['birthDay']) <16){
                        $text .= $line."：".L('staffProfiles.other.age_warn')."<br>";
                    } elseif(!empty($field['education']) && !in_array($field['education'],$education)){
                        $text .= $line."：".L('staffProfiles.other.education_range')."<br>";
                    }elseif(!empty($field['nation']) && !in_array($field['nation'],$nationOption)){
                        $text .= $line."：".L('staffProfiles.other.nation_range')."<br>";
                    }elseif(!empty($field['health']) && !in_array($field['health'],$healthOption)){
                        $text .= $line."：".L('staffProfiles.other.health_range')."<br>";
                    }elseif(!empty($field['jobTitle']) && !in_array($field['jobTitle'],$jobTitleOption)){
                        $text .= $line."：".L('staffProfiles.other.jobTitle_range')."<br>";
                    }elseif(!empty($field['politicsStatus']) && !in_array($field['politicsStatus'],$politicsStatus)){
                        $text .= $line."：".L('staffProfiles.other.politicsStatus_range')."<br>";
                    }elseif(!empty($field['residenceType']) && !in_array($field['residenceType'],$this->residenceTypeOption)){
                        $text .= $line."：".L('staffProfiles.other.residenceType_range')."<br>";
                    }else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= $line."：".L('job.other.import_success')."<br>";
                        } else {
                            $text .= $line."：".L('job.other.import_failed')."<br>";
                        }
                    }
                }
            }
            $text =str_replace(['{{staffName}}','{{fileName}}'],[$this->control['name'],$_FILES['file']['name']],L('job.other.import_log'))  .  '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = str_replace(['{{$x}}'],[$x],L('job.other.import_warn'));
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 设置状态
     * @return bool|string
     */
    public function setWorkFlow()
    {
        $idArr = $this->get('id') ? [$this->get('id')] : $this->post('listId');
        $state = $this->get('state');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] =L('staffProfiles.talentPool.edit_permission');
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = L('staffProfiles.talentPool.chooseData');
        } elseif (!in_array($state, explode('，', para('talentPoolState')))) {
            $json['warn'] = L('staffProfiles.talentPool.type_error');
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text=str_replace(['{{staffName}}','{{state}}','{{id}}'],[$this->control['name'],$state,implode("','", $idArr)],L('staffProfiles.talentPool.workFlowEditText'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }



    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('staffProfiles.tip.permission_export_warn');
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = [L('staffProfiles.table.name'), L('staffProfiles.table.sex'), L('staffProfiles.table.tel'), L('staffProfiles.table.appliedJob'), L('staffProfiles.table.expect_address'), L('staffProfiles.table.expect_salary'), L('staffProfiles.table.idCard'), L('staffProfiles.table.birthDay'), L('staffProfiles.table.email'), L('staffProfiles.table.nation'), L('staffProfiles.table.homeTown'), L('staffProfiles.table.height').'(cm)', L('staffProfiles.table.weight').'(kg)', L('staffProfiles.table.health'), L('staffProfiles.table.education'), L('staffProfiles.table.major'), L('staffProfiles.table.college'),
                L('staffProfiles.table.workInDate'), L('staffProfiles.table.marriage'), L('staffProfiles.table.politicsStatus'), L('staffProfiles.table.residenceAddress'), L('staffProfiles.table.residenceType'), L('staffProfiles.table.liveAddress'), L('staffProfiles.table.postCode'), L('staffProfiles.table.secContactName'), L('staffProfiles.table.secContactRelation'), L('staffProfiles.table.secContactTel'), L('staffProfiles.talentPool.channels'), L('staffProfiles.table.text')];
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $job = query("job", " id = '$array[jobId]' ");
                    $data[] = [$array['name'], $array['name'], $array['tel'], $job['name'], $array['exWorkPlace'], $array['exSalary'], $array['idCard'],
                        self::null($array['birthDay']), $array['email'], $array['nation'], $array['homeTown'], $array['height'], $array['weight'], $array['health'], $array['education'],
                        $array['major'], $array['college'], $array['workDate'], $array['marriage'], $array['politicsStatus'], $array['residenceAddress'], $array['residenceType'], $array['liveAddress'],
                        $array['postCode'], $array['secContactName'], $array['secContactRelation'], $array['secContactTel'], $array['source'], $array['text']];
                }
            }
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('staffProfiles.talentPool.exportLog'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('staffProfiles.talentPool.talentForm').".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 获取招聘组成员姓名
     * @param $teamStid
     * @return string
     */
    public function findTeamStName($teamStid): string
    {
        $staffText = '';
        $staffArr = explode(',', $teamStid);
        foreach ($staffArr as $stid) {
            $staffText .= ',' . self::findStaff($stid);
        }
        return $staffText ? ltrim($staffText, ',') : '';
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        /*****学习经历*********/
        $educationTr[] =[L('staffProfiles.table.study_date'),
            L('staffProfiles.table.university'),
            L('staffProfiles.table.study_major'),
            L('staffProfiles.table.achievements'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "study_history", 'where' => "talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $educationTr[] = [
                hidden(array('name' => 'studyId[]', 'value' => $array['id'])) .
                text(array('name' => 'educationDate[]', 'value' => $array['studyDate'], 'laydate' => ['range' => '~'])),
                text(array('name' => 'school[]', 'value' => $array['college'])),
                text(array('name' => 'schoolMajor[]', 'value' => $array['major'])),
                text(array('name' => 'certificate[]', 'value' => $array['certificate'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }

        /*****工作经历*********/
        $workTr[] =  [L('staffProfiles.table.work_date_start'),
            L('staffProfiles.table.employed'),
            L('staffProfiles.table.station'),
            L('staffProfiles.table.work_content'),
            L('staffProfiles.table.quit_reason'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "job_history", 'where' => "talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $workTr[] = [
                hidden(array('name' => 'workId[]', 'value' => $array['id'])) .
                text(array('name' => 'workDate[]', 'value' => $array['workDate'], 'laydate' => ['range' => '~'])),
                text(array('name' => 'companyName[]', 'value' => $array['companyName'])),
                text(array('name' => 'position[]', 'value' => $array['position'])),
                text(array('name' => 'content[]', 'value' => $array['content'])),
                text(array('name' => 'cause[]', 'value' => $array['cause'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }

        /*****家庭成员*********/
        $familyTr[] = [L('staffProfiles.table.name'),
            L('staffProfiles.table.relationship'),
            L('staffProfiles.table.work_unit'),
            L('staffProfiles.table.contactTel'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "talent_family ", 'where' => " talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $familyTr[] = [
                hidden(array('name' => 'familyId[]', 'value' => $array['id'])) .
                text(array('name' => 'memberName[]', 'value' => $array['name'])),
                text(array('name' => 'relation[]', 'value' => $array['relation'])),
                text(array('name' => 'memberCompany[]', 'value' => $array['company'])),
                text(array('name' => 'contactTel[]', 'value' => $array['contactTel'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }


        //按钮
	    $button[]  = [
		    "name"  => L('public.save'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun" => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-blue-bg',
	    ];
	    $button[]  = [
		    "name"  => L('public.saveDraft'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-green-bg',
	    ];
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    must . L('staffProfiles.table.name')."：" => text(["name" => "name", "value" => $info['name']]),
                    must . L('staffProfiles.table.sex')."：" => radio(["name" => "sex", 'value' => ['男', '女'], "checked" => $info['sex']]),
                ],
                [
                    must . L('staffProfiles.table.tel')."：" => text(["name" => "tel", "value" => $info['tel']]),
                    must . L('staffProfiles.table.appliedJob')."：" => selectMultiple([
                        "name" => "jobId", "title" => L('staffProfiles.table.appliedJob'),
                        'value' => $info['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                    ]),
                ],
                [
                    must . L('staffProfiles.table.education')."：" => select(array('name' => 'education', 'title' => L('staffProfiles.table.education'), 'class' => 'select', 'value' => $info['education'], 'option' => explode('，', para('education')))),
                    L('staffProfiles.table.email')."：" => text(["name" => "email", "value" => $info['email']]),
                ],
                [
                    "期望薪资：" => select(array('name' => 'exSalary', 'title' => L('staffProfiles.table.expect_salary'), 'class' => 'select', 'value' => $info['exSalary'], 'option' => explode('，', para('exSalary')))),
                    "期望工作地点：" => select(array('name' => 'exWorkPlace', 'title' => L('staffProfiles.table.expect_address'), 'class' => 'select', 'value' => $info['exWorkPlace'], 'option' => explode('，', para('exWorkPlace'))))
                ],
                [
                    L('staffProfiles.table.idCard')."：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
                    L('staffProfiles.table.birthDay')."：" => text(["name" => "birthDay", 'laydate' => [], "value" => self::null($info['birthDay'], false)]),
                ],
                [
                    L('staffProfiles.table.nation')."：" => select(array('name' => 'nation', 'title' => L('staffProfiles.table.nation'), 'class' => 'select', 'value' => $info['nation'], 'option' => explode('、', para('nationOption')))),
                    L('staffProfiles.table.homeTown')."：" => repeatSelect(array('name' => 'homeTown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown']))
                ],
                [
                    L('staffProfiles.table.height')."：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
                    L('staffProfiles.table.weight')."：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : ''])
                ],
                [
                    L('staffProfiles.table.college')."：" => text(["name" => "college", "value" => $info['college']]),
                    L('staffProfiles.table.major')."：" => text(["name" => "major", "value" => $info['major']]),
                ],
                [
                    L('staffProfiles.table.workInDate')."：" => text(["name" => "workInDate", 'laydate' => [], "value" => $info['workDate']]),
                    L('staffProfiles.table.health')."：" => select(array('name' => 'health', 'title' => '健康状况', 'class' => 'select', 'value' => $info['health'], 'option' => explode('，', para('healthOption'))))
                ],
                [
                    L('staffProfiles.table.marriage')."：" => radio(["name" => "marriage", 'value' => $this->marryOption, "checked" => $info['marriage']]),
                    L('staffProfiles.table.politicsStatus')."：" => select(array('name' => 'politicsStatus', 'title' => L('staffProfiles.table.politicsStatus'), 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => explode('，', para('politicsStatus')))),
                ],
                [
                    L('staffProfiles.table.residenceAddress')."：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
                    L('staffProfiles.table.residenceType')."：" => radio(["name" => "residenceType", 'value' => $this->residenceTypeOption, "checked" => $info['residenceType']]),

                ],
                [
                    L('staffProfiles.table.liveAddress')."：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
                    L('staffProfiles.table.postCode')."：" => text(["name" => "postCode", "value" => $info['postCode']]),
                ],
                [
                    L('staffProfiles.table.secContactName')."：" => text(["name" => "secContactName", "value" => $info['secContactName']]),
                    L('staffProfiles.table.secContactRelation')."：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
                ],
                [
                    L('staffProfiles.table.secContactTel')."：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
                ],
                [
                    L('staffProfiles.talentPool.channels')."：" => select(array('name' => 'sourceType', 'title' => L('staffProfiles.table.choose'), 'class' => 'select', 'value' => $info['source'], 'option' => explode('，', para('talentSourceOption')))),
                ],
                [
                    L('staffProfiles.table.text')."：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.table.learning_experience')."</span>"
                ],
                [
                    $this->tableMany(array('tr' => $educationTr, 'method' => "addRow(this,'education')", 'end' => true, 'button' => true))
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.table.work_experience')."</span>"
                ],
                [
                    $this->tableMany(array('tr' => $workTr, 'end' => true, 'method' => "addRow(this,'work')", 'button' => true))
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.table.family_member')."</span>"
                ],
                [
                    $this->tableMany(array('tr' => $familyTr, 'end' => true, 'method' => "addRow(this,'family')", 'button' => true))
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.table.enclosure')."</span>"
                ],
                [
                    fileUploadClass::addFileComponent($info['id'], '人才库', self::page, self::page . 'EditForm'),
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
            'button' => ' '
        ]);
        $data['html'] .= $this->editJs();

        //返回
        return $this->tab($data);
    }

    public function editJs()
    {
        return <<<eof
<script>
 function getBirthDay(e){
        let IdCard = e.value;
        let birthDay = $("[name='birthDay']").val();
        if (IdCard.length ===18 && !birthDay){
            //获取出生日期
            $("[name='birthDay']").val(IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14))
        }
    }
     //添加一行
     function addRow(e,type){
         $.post(root+'control/adIndex.html?cla=talentPool&fun=addRow',{type:type},function (res){
             $(e).parent().before(res.data);
         },'json');
     }
     function getJobInfo(e){
       let id = e.value;
       $.post(root+'control/adIndex.html?cla=talentPool&fun=getJobInfo',{id:id},function(res) {
            $("#jobType").html(res.data.jobType);
             $("#department").html(res.data.department);
       },'json')
     }
     function delSingleIco(id){
      $.post(root+'control/adIndex.html?cla=talentPool&fun=delIco',{id:id},function(res) {
            if (res.warn ==2){
                $("[data-type='"+res.data.type+"']").attr('src',root+'img/images/emptyImg.jpg')
                 $("[data-type='"+res.data.type+"']").parent().parent().find(".edit-ico").attr('src',root+'img/images/clickEdit.png');
                 $("[data-type='"+res.data.type+"']").parent().parent().find(".edit-ico").attr('onclick',"clickUpload('"+res.data.type+"','"+res.data.id+"')")
            }else{
                msg(res.warn,'error')
            }
       },'json')
     }
</script>
eof;

    }

    public function getJobInfo(): bool|string
    {
        $job = query('job', "id = '" . $this->post('id') . "'");
        $json['data'] = [
            'department' => departmentClass::getTypeName($job['departmentId']),
            'jobType' => $job['type']
        ];
        return json_encode($json, 320);
    }

    public function delIco()
    {
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('staffProfiles.talentPool.edit_permission');
        } elseif (empty($id)) {
            $json['warn'] = L('staffProfiles.talentPool.no_id');
        } else {
            $file = query('file', "id = '$id'");
            $json['warn'] = delete(array('table' => 'file', 'where' => "id = '$id'"));
            if ($json['warn'] == '删除成功') {
                fileDelete($file['src']);
                $json['data']['id'] = $file['targetId'];
                $json['data']['type'] = $file['target'];
                $text=str_replace(['{{staffName}}','{{fileName}}','{{type}}','{{id}}'],[$this->control['name'],$file['name'],$file['target'],$id],L('staffProfiles.talentPool.delFile'));
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    public function saveIco($page, $id, $type, $fileArr): bool|string
    {
        $result = $this->saveFile($fileArr['imgFile'], 'talentPool', explode(',', para('fileFormat')));
        if (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $file = query('file', "targetId = '$id' and target = '$type'");
            if (empty($file['id'])) {
                $suiji = suiji();
                $json['warn'] = static::insert(array(
                    'table' => 'file',
                    'field' => [
                        'id' => $suiji,
                        'stid' => self::$stid,
                        'targetId' => $id,
                        'target' => $type,
                        'name' => $result['fileName'],
                        'format' => $result['suffix'],
                        'size' => $result['size'],
                        'src' => $result['src']
                    ]
                ));
            } else {
                $json['warn'] = static::update(array(
                    'table' => 'file',
                    'field' => [
                        'name' => $result['fileName'],
                        'format' => $result['suffix'],
                        'size' => $result['size'],
                        'src' => $result['src']
                    ],
                    'where' => "id = '$file[id]'"
                ));
                $suiji = $file['id'];
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{fileName}}','{{type}}','{{id}}'],[$this->control['name'],$result['fileName'],$type,$suiji],L('staffProfiles.talentPool.saveIco'));
                $this->logText(["type" => $page, "text" => $text]);
            }
            //添加日志
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['id'] = $suiji;
            }
        }
        return json_encode($json, 320);
    }

    /**
     *上传身份证明图片
     */
    function uploadIco()
    {
        $type = $this->post('type');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('staffProfiles.talentPool.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('staffProfiles.tip.find_none_staff');
        } else {
            return $this->saveIco(self::page, $info['id'], $type, $_FILES);
        }
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        $html = '';
        switch ($type) {
            case 'education':
                $html = "
                <tr>
                <td>" . hidden(array('name' => 'studyId[]', 'value' => self::getId())) . text(array('name' => 'educationDate[]', 'laydate' => ['range' => '~'])) . "</td>
                <td>" . text(array('name' => 'school[]')) . "</td>
                <td>" . text(array('name' => 'schoolMajor[]')) . "</td>
                <td>" . text(array('name' => 'certificate[]')) . "</td>
                <td><span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span></td>
</tr>
                ";
                break;
            case 'work':
                $html = "
                <tr>
                <td>" . hidden(array('name' => 'workId[]', 'value' => self::getId())) . text(array('name' => 'workDate[]', 'laydate' => ['range' => '~'])) . "</td>
                <td>" . text(array('name' => 'companyName[]')) . "</td>
                <td>" . text(array('name' => 'position[]')) . "</td>
                <td>" . textarea(array('name' => 'content[]')) . "</td>
                <td>" . text(array('name' => 'cause[]')) . "</td>
                <td><span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span></td>
</tr>
                ";
                break;
            case 'family':
                $html = "
                <tr>
                <td>" . hidden(array('name' => 'familyId[]', 'value' => self::getId())) . text(array('name' => 'memberName[]')) . "</td>
                <td>" . text(array('name' => 'relation[]')) . "</td>
                <td>" . text(array('name' => 'memberCompany[]')) . "</td>
                <td>" . text(array('name' => 'contactTel[]')) . "</td>
                <td><span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span></td>
</tr>
                ";
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    /**
     * 编辑保存
     * @return bool|string
     */
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'tel' => $this->post('tel'),
            'jobId' => $this->post('jobId'),
            'exWorkPlace' => $this->post('exWorkPlace'),
            'exSalary' => $this->post('exSalary'),
            'idCard' => $this->post('idCard'),
            'birthDay' => $this->post('birthDay'),
            'nation' => $this->post('nation'),
            'homeTown' => $this->post('homeTown'),
            'height' => $this->post('height'),
            'weight' => $this->post('weight'),
            'health' => $this->post('health'),
            'education' => $this->post('education'),
            'major' => $this->post('major'),
            'college' => $this->post('college'),
            'workDate' => $this->post('workInDate'),
            'marriage' => $this->post('marriage'),
            'politicsStatus' => $this->post('politicsStatus'),
            'residenceAddress' => $this->post('residenceAddress'),
            'liveAddress' => $this->post('liveAddress'),
            'secContactName' => $this->post('secContactName'),
            'secContactTel' => $this->post('secContactTel'),
            'secContactRelation' => $this->post('secContactRelation'),
            'jobTitle' => $this->post('jobTitle'),
            'text' => $this->post('text'),
            'postCode' => $this->post('postCode'),
            'email' => $this->post('email'),
            'source' => $this->post('sourceType'),
            'residenceType' => $this->post('residenceType'),
        ];
        $annotation = [
            'name' => L('staffProfiles.table.name'),
            'sex' => L('staffProfiles.table.sex'),
            'tel' => L('staffProfiles.table.tel'),
            'jobId' => L('staffProfiles.table.appliedJob'),
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'tel' => 'required|tel',
            'jobId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();

        //学习经历
        $studyIdArr = $this->post('studyId') ?? [];
        $educationDateArr = $this->post('educationDate');
        $schoolArr = $this->post('school');
        $schoolMajorArr = $this->post('schoolMajor');
        $certificateArr = $this->post('certificate');
        //工作经历
        $workIdArr = $this->post('workId') ?? [];
        $workDateArr = $this->post('workDate');
        $companyNameArr = $this->post('companyName');
        $positionArr = $this->post('position');
        $contentArr = $this->post('content');
        $causeArr = $this->post('cause');
        //家庭成员
        $familyIdArr = $this->post('familyId') ?? [];
        $memberNameArr = $this->post('memberName');
        $relationArr = $this->post('relation');
        $memberCompanyArr = $this->post('memberCompany');
        $contactTelArr = $this->post('contactTel');
        //附件
        $fileIdArr = $this->post('fileId');
        $staffObj = new staffProfilesClass();
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.talentPool.edit_permission');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        } elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
            $json['warn'] = L('staffProfiles.tip.name_warn');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = L('staffProfiles.tip.email_warn');
        } elseif (!empty($field['idCard']) && (static::total(array('sql' => "SELECT count(*) AS total FROM " . self::table . " where idCard = '{$field['idCard']}' and id !='$id'")))) {
            $json['warn'] =L('staffProfiles.tip.idCard_repeat_warn');
        } elseif(!empty($field['birthDay']) && $staffObj->age($field['birthDay']) <16){
            $json['warn'] =  L('staffProfiles.tip.age_warn');
        } else {
            $this->startTrans();//开启事务
            $isPass = true;//事务通过标志
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'state' => '人才登记',
                    'workFlow' => 0,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            //添加或更新学习经历
            if (is_array($studyIdArr)) {
                foreach ($studyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'study_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'study_history',
                            "field" => [
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'study_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新工作经历
            if (is_array($workIdArr)) {
                foreach ($workIdArr as $k => $nid) {
                    if (static::total(array('table' => 'job_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'job_history',
                            "field" => [
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'job_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新家庭成员
            if (is_array($familyIdArr)) {
                foreach ($familyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'talent_family',
                            "field" => [
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'talent_family',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    $isPass = false;
                }
            }
            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务

                //删除不在此ID中的数据
                delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$id' "));
                delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$id'"));
                delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$id'"));

                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['name'],$id],L('staffProfiles.talentPool.talentEditLog'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 入职页
     * @return string
     */
    public function entry(): string
    {

        $info = query(self::table, " id = '" . $this->get('id') . "' ");

        /*****学习经历*********/
        $educationTr[] = [L('staffProfiles.table.study_date'),
            L('staffProfiles.table.university'),
            L('staffProfiles.table.study_major'),
            L('staffProfiles.table.achievements'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "study_history where talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $educationTr[] = [
                hidden(array('name' => 'studyId[]', 'value' => $array['id'])) .
                text(array('name' => 'educationDate[]', 'value' => $array['studyDate'], 'laydate' => ['range' => '~'])),
                text(array('name' => 'school[]', 'value' => $array['college'])),
                text(array('name' => 'schoolMajor[]', 'value' => $array['major'])),
                text(array('name' => 'certificate[]', 'value' => $array['certificate'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }

        /*****工作经历*********/
        $workTr[] = [L('staffProfiles.table.work_date_start'),
            L('staffProfiles.table.employed'),
            L('staffProfiles.table.station'),
            L('staffProfiles.table.work_content'),
            L('staffProfiles.table.quit_reason'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "job_history where talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $workTr[] = [
                hidden(array('name' => 'workId[]', 'value' => $array['id'])) .
                text(array('name' => 'workDate[]', 'value' => $array['workDate'], 'laydate' => ['range' => '~'])),
                text(array('name' => 'companyName[]', 'value' => $array['companyName'])),
                text(array('name' => 'position[]', 'value' => $array['position'])),
                textarea(array('name' => 'content[]', 'value' => $array['content'])),
                text(array('name' => 'cause[]', 'value' => $array['cause'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }

        /*****家庭成员*********/
        $familyTr[] = [L('staffProfiles.table.name'),
            L('staffProfiles.table.relationship'),
            L('staffProfiles.table.work_unit'),
            L('staffProfiles.table.contactTel'),
            L('staffProfiles.table.operation')];
        $result = find(array('table' => "talent_family where talentId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $familyTr[] = [
                hidden(array('name' => 'familyId[]', 'value' => $array['id'])) .
                text(array('name' => 'memberName[]', 'value' => $array['name'])),
                text(array('name' => 'relation[]', 'value' => $array['relation'])),
                text(array('name' => 'memberCompany[]', 'value' => $array['company'])),
                text(array('name' => 'contactTel[]', 'value' => $array['contactTel'])),
                "<span class='del-row-button' onclick='decline(this)'>".L('staffProfiles.button.del')."</span>"
            ];
        }


        /*******附件****************/
        //入职信息
        $entry = query('staff_entry_record', " talentId = '$info[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1) order by time desc");


        $button = $photo = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                "name" => L('staffProfiles.table.save'),
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EntryForm',root+'control/adIndex.html?cla=" . self::page . "&fun=entryEdit')",
                "post" => ["id" => $this->get('id')],
            ];
            $ico = [];
            $all = find(array('table' => 'file', 'where' => "targetId = '$info[id]' and target in ('入职登记表','身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书','竞业限制协议')"));
            foreach ($all['array'] as $array) {
                $ico[$array['target']] = ['id' => $array['id'], 'src' => $array['src']];
            }
            $photo = array(
                array("title" => L('staffProfiles.table.front_of_id_card'), 'type' => '身份证正面', "url" => $ico['身份证正面']['src'] ?? '', "fileId" => $ico['身份证正面']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.back_of_id_card'), 'type' => '身份证背面', "url" => $ico['身份证背面']['src'] ?? '', "fileId" => $ico['身份证背面']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.diploma'), 'type' => '毕业证', "url" => $ico['毕业证']['src'] ?? '', "fileId" => $ico['毕业证']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.degree_diploma'), 'type' => '学位证', "url" => $ico['学位证']['src'] ?? '', "fileId" => $ico['学位证']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.bank_card'), 'type' => '银行卡', "url" => $ico['银行卡']['src'] ?? '', "fileId" => $ico['银行卡']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.registration_form'), 'type' => '入职登记表', "url" => $ico['入职登记表']['src'] ?? '', "fileId" => $ico['入职登记表']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.leaving_certificate'), 'type' => '离职证明', "url" => $ico['离职证明']['src'] ?? '', "fileId" => $ico['离职证明']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.medical_report'), 'type' => '体检报告', "url" => $ico['体检报告']['src'] ?? '', "fileId" => $ico['体检报告']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.Professional_certificate'), 'type' => '职称证书', "url" => $ico['职称证书']['src'] ?? '', "fileId" => $ico['职称证书']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.competition_agreement'), 'type' => '竞业限制协议', "url" => $ico['竞业限制协议']['src'] ?? '', "fileId" => $ico['竞业限制协议']['id'] ?? '', "id" => $info['id']),
            );
        }
        $entry['contractLimitType'] = $entry['contractLimitType'] ?: '固定期限';
        $entry['contractYear'] = !$entry['contractYear'] && $entry['contractLimitType'] == '固定期限' ? 3 : $entry['contractYear'];//默认3年
        $job = query('job', "id = '$info[jobId]'");
        $departmentName = departmentClass::getTypeName($job['departmentId']);

        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    must . L('staffProfiles.table.name')."：" => text(["name" => "name", "value" => $info['name']]),
                    must . L('staffProfiles.table.sex')."：" => radio(["name" => "sex", 'value' => ['男', '女'], "checked" => $info['sex']]),
                ],
                [
                    must . L('staffProfiles.table.tel')."：" => text(["name" => "tel", "value" => $info['tel']]),
                    must . L('staffProfiles.table.appliedJob')."：" => selectMultiple([
                        "name" => "jobId", "title" => L('staffProfiles.table.appliedJob'),
                        'value' => $info['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                    ]),
                ],
                [
                    must . L('staffProfiles.table.education')."：" => select(array('name' => 'education', 'title' => L('staffProfiles.table.education'), 'class' => 'select', 'value' => $info['education'], 'option' => explode('，', para('education')))),
                    L('staffProfiles.table.email')."：" => text(["name" => "email", "value" => $info['email']]),
                ],
                [
                    L('staffProfiles.table.expect_salary')."：" => select(array('name' => 'exSalary', 'title' => L('staffProfiles.table.expect_salary'), 'class' => 'select', 'value' => $info['exSalary'], 'option' => explode('，', para('exSalary')))),
                    L('staffProfiles.table.expect_address')."：" => select(array('name' => 'exWorkPlace', 'title' => L('staffProfiles.table.expect_address'), 'class' => 'select', 'value' => $info['exWorkPlace'], 'option' => explode('，', para('exWorkPlace'))))
                ],
                [
                    must .L('staffProfiles.table.idCard')."：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
                    L('staffProfiles.table.birthDay')."：" => text(["name" => "birthDay", 'laydate' => [], "value" => self::null($info['birthDay'], false)]),
                ],
                [
                    L('staffProfiles.table.nation')."：" => select(array('name' => 'nation', 'title' => L('staffProfiles.table.nation'), 'class' => 'select', 'value' => $info['nation'], 'option' => explode('、', para('nationOption')))),
                    L('staffProfiles.table.homeTown')."：" => repeatSelect(array('name' => 'homeTown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown']))
                ],
                [
                    L('staffProfiles.table.height')."：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
                    L('staffProfiles.table.weight')."：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : ''])
                ],
                [
                    L('staffProfiles.table.college')."：" => text(["name" => "college", "value" => $info['college']]),
                    L('staffProfiles.table.major')."：" => text(["name" => "major", "value" => $info['major']]),
                ],
                [
                    L('staffProfiles.table.workInDate')."：" => text(["name" => "workInDate", 'laydate' => [], "value" => $info['workDate']]),
                    L('staffProfiles.table.health')."：" => select(array('name' => 'health', 'title' => '健康状况', 'class' => 'select', 'value' => $info['health'], 'option' => explode('，', para('healthOption'))))
                ],
                [
                    L('staffProfiles.table.marriage')."：" => radio(["name" => "marriage", 'value' => $this->marryOption, "checked" => $info['marriage']]),
                    L('staffProfiles.table.politicsStatus')."：" => select(array('name' => 'politicsStatus', 'title' => L('staffProfiles.table.politicsStatus'), 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => explode('，', para('politicsStatus')))),
                ],
                [
                    L('staffProfiles.table.residenceAddress')."：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
                    L('staffProfiles.table.residenceType')."：" => radio(["name" => "residenceType", 'value' => $this->residenceTypeOption, "checked" => $info['residenceType']]),

                ],
                [
                    L('staffProfiles.table.liveAddress')."：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
                    L('staffProfiles.table.postCode')."：" => text(["name" => "postCode", "value" => $info['postCode']]),
                ],
                [
                    L('staffProfiles.table.secContactName')."：" => text(["name" => "secContactName", "value" => $info['secContactName']]),
                    L('staffProfiles.table.secContactRelation')."：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
                ],
                [
                    L('staffProfiles.table.secContactTel')."：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
                ],
                [
                    L('staffProfiles.talentPool.channels')."：" => select(array('name' => 'sourceType', 'title' => '请选择', 'class' => 'select', 'value' => $info['source'], 'option' => explode('，', para('talentSourceOption')))),
                ],
                [
                    L('staffProfiles.table.text')."：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
                [
                    "<div><span class='small-title'>".L('staffProfiles.detail.work_info')."</span></div>"
                ],
                [
                    must . L('staffProfiles.table.entryDate')."：" => text(["name" => "entryDate", 'laydate' => [], "value" => $entry['entryDate']]),
                    must . L('staffProfiles.table.tryDate')."：" => text(["name" => "endDate", 'laydate' => [], "value" => $entry['endDate']]),
                ],
                [
                    must . L('staffProfiles.table.contractType')."：" => radio(["name" => "contractType", 'value' => explode('，', para('contractTypeOption')), "checked" => $entry['contractType'] ?: '劳动合同']),
                    must . L('staffProfiles.table.contractyear')."：" => radio(array('name' => 'contractLimitType', 'checked' => $entry['contractLimitType'], 'value' => ['固定期限' => '固定期限' . "&nbsp;<input name='contractYear' min='0' style='padding:5px;width: 100px' type='number' value='{$entry['contractYear']}'>&nbsp;月&nbsp;&nbsp;", '无固定期限' => '无固定期限'])),
                ],
                [
                    must . L('staffProfiles.talentPool.beJob')."：" => selectMultiple([
                        "name" => "jobId", "title" => L('staffProfiles.talentPool.beJob'),
                        'value' => $entry['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                        'where' => "1=1 order by list",
                        'change' => 'getJobInfo'
                    ]),
                    L('job.table.jobType').'：' => "<span id='jobType'>{$job['type']}</span>",
                ],
                [
                    L('job.table.department_name').'：' => "<span id='department'>{$departmentName}</span>",
                    L('staffProfiles.table.superior')."：" => selectMultiple([
                        "name" => "managerId", "title" => L('staffProfiles.table.superior'),
                        'value' => $entry['managerId'],
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                    ]),
                ],
                [
                    must . L('staffProfiles.table.workSalary')."：" => text(["name" => "workSalary", "value" => $entry['workSalary']]),
                    must . L('staffProfiles.table.insure')."：" => text(["name" => "insure", "value" => $entry['insure']]),
                ],
                [
                    L('staffProfiles.table.work_text')."：" => textarea(["name" => "workText", "value" => $entry['text']]),
                ],
                [
                    "
<div><span class='small-title'>".L('staffProfiles.table.learning_experience')."</span></div>
<div class='purchaseMx' style='margin-top: 5px'>" . $this->tableMany(array('tr' => $educationTr, 'method' => "addRow(this,'education')", 'end' => true, 'button' => true)) . "</div>"
                ],
                [
                    "
<div><span class='small-title'>".L('staffProfiles.table.work_experience')."</span></div>
<div class='purchaseMx' style='margin-top: 5px'>" . $this->tableMany(array('tr' => $workTr, 'end' => true, 'method' => "addRow(this,'work')", 'button' => true)) . "</div>"
                ],
                [
                    "
<div><span class='small-title'>".L('staffProfiles.table.family_member')."</span></div>
<div class='purchaseMx' style='margin-top: 5px'>" . $this->tableMany(array('tr' => $familyTr, 'end' => true, 'method' => "addRow(this,'family')", 'button' => true)) . "</div>"
                ],
                [
                    "
<div><span class='small-title'>".L('staffProfiles.table.enclosure')."</span></div>" . fileUploadClass::addFileComponent($info['id'], '人才库', self::page, self::page . 'EntryForm'),
                ],
                [
                    "<div><span class='small-title'>".L('staffProfiles.table.entry_data')."</div><span class='small-title'>"
                ],
                [
                    $this->photo($photo)
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $this->get('id'))) . hidden(array('name' => 'source', 'value' => $this->get('source'))) . "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EntryForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco')\"></div>",
            'button' => ' '
        ]);
        $data['html'] .= $this->editJs();


        //返回
        return $this->tab($data);
    }


    /**
     * @param $data
     * @return string
     */
    public function photo($data): string
    {
        $li = "";
        foreach ($data as $num => $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['type']}')\" class='clickIco edit-ico'>";
                if (!empty($array['fileId'])) {
                    $click = "<img  src='" . root . "img/control/singleDel.svg' onClick=\"delSingleIco('{$array['fileId']}')\" class='clickIco edit-ico'>";
                }
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        return <<<efo
		<div class='imgSingle' style="margin: 10px 10px 10px 0">
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div>

		<script>
		//点击上传图片
        function clickUpload(type,id=''){
            $('[name=type]').val(type)
            $('#imgFile').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let type= $('[name=type]').val();
            let formData = new FormData(form);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='imgFile']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('src',root+'img/control/singleDel.svg');
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('onclick',"delSingleIco('"+result.data.id+"')")
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
    }

    /**
     *入职信息保存
     */
    public function entryEdit()
    {

        $id = $this->post('id') ?: self::getId();
        $field = [
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'tel' => $this->post('tel'),
            'idCard' => $this->post('idCard'),
            'birthDay' => $this->post('birthDay'),
            'nation' => $this->post('nation'),
            'homeTown' => $this->post('homeTown'),
            'height' => $this->post('height'),
            'weight' => $this->post('weight'),
            'health' => $this->post('health'),
            'education' => $this->post('education'),
            'major' => $this->post('major'),
            'college' => $this->post('college'),
            'workDate' => $this->post('workInDate'),
            'marriage' => $this->post('marriage'),
            'politicsStatus' => $this->post('politicsStatus'),
            'residenceAddress' => $this->post('residenceAddress'),
            'liveAddress' => $this->post('liveAddress'),
            'secContactName' => $this->post('secContactName'),
            'secContactTel' => $this->post('secContactTel'),
            'secContactRelation' => $this->post('secContactRelation'),
            'jobTitle' => $this->post('jobTitle'),
            'text' => $this->post('text'),
            'postCode' => $this->post('postCode'),
            'email' => $this->post('email'),
            'source' => $this->post('sourceType'),
            'residenceType' => $this->post('residenceType'),
        ];
        $annotation = [
            'name' => L('staffProfiles.table.name'),
            'sex' => L('staffProfiles.table.sex'),
            'tel' => L('staffProfiles.table.tel'),
            'idCard' => L('staffProfiles.table.idCard'),
            'education' => L('staffProfiles.table.education'),
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'tel' => 'required|tel',
            'idCard' => 'required|id_card',
            'education' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $entryField = [
            'jobId' => $this->post('jobId'),
            'managerId' => $this->post('managerId'),
            'entryDate' => $this->post('entryDate'),
            'endDate' => $this->post('endDate'),
            'text' => $this->post('workText'),
            'contractType' => $this->post('contractType'),
            'contractYear' => $this->post('contractYear'),
            'contractLimitType' => $this->post('contractLimitType'),
            'workSalary' => $this->post('workSalary'),
            'insure' => $this->post('insure'),
        ];
        $enAnnotation = [
            'jobId' => L('staffProfiles.talentPool.beJob'),
            'entryDate' => L('staffProfiles.table.entryDate'),
            'endDate' => L('staffProfiles.table.tryDate'),
            'contractType' =>  L('staffProfiles.table.contractType'),
            'contractLimitType' =>  L('staffProfiles.table.contractyear'),
            'workSalary' => L('staffProfiles.table.workSalary'),
            'insure' => L('staffProfiles.table.insure'),
        ];
        $enRules = [
            'jobId' => 'required',
            'entryDate' => 'required',
            'endDate' => 'required',
            'contractType' => 'required',
            'contractLimitType' => 'required',
            'workSalary' => 'required',
            'insure' => 'required',
        ];
        // 校验是否符合规则
        $entryResult = $vt->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //学习经历
        $studyIdArr = $this->post('studyId') ?? [];
        $educationDateArr = $this->post('educationDate');
        $schoolArr = $this->post('school');
        $schoolMajorArr = $this->post('schoolMajor');
        $certificateArr = $this->post('certificate');
        //工作经历
        $workIdArr = $this->post('workId') ?? [];
        $workDateArr = $this->post('workDate');
        $companyNameArr = $this->post('companyName');
        $positionArr = $this->post('position');
        $contentArr = $this->post('content');
        $causeArr = $this->post('cause');
        //家庭成员
        $familyIdArr = $this->post('familyId') ?? [];
        $memberNameArr = $this->post('memberName');
        $relationArr = $this->post('relation');
        $memberCompanyArr = $this->post('memberCompany');
        $contactTelArr = $this->post('contactTel');
        //附件
        $fileIdArr = $this->post('fileId');

        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if ($this->post('source')) {
            //来源为入职记录
            $power = $this->post('source');
        } else {
            $power = self::page;
        }
        $staffObj = new staffProfilesClass();
        //判断
        if (!$this->power($power, "edit")) {
            $json['warn'] = L('staffProfiles.talentPool.edit_permission');
        } elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
            $json['warn'] = L('staffProfiles.tip.name_warn');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = L('staffProfiles.tip.email_warn');
        } elseif (!empty($field['idCard']) && (static::total(array('table' => self::table, 'where' => " and idCard = '{$field['idCard']}' and id !='$id'")))) {
            $json['warn'] =L('staffProfiles.tip.idCard_repeat_warn');
        }  elseif(!empty($field['birthDay']) && $staffObj->age($field['birthDay']) <16){
            $json['warn'] =  L('staffProfiles.tip.age_warn');
        }elseif (!$info['id']) {
            $json['warn'] = L('staffProfiles.tip.find_none_staff');
        } else {
            $this->startTrans();//开启事务
            $isPass = true;//事务通过标志
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => $where
            ]);

            /******工作信息*******/
            $entryRecord = query('staff_entry_record', " talentId = '$info[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1) order by time desc");
            if (!empty($entryRecord['id'])) {
                //更新
                $warn = static::update(array('table' => 'staff_entry_record', 'field' => $entryField, 'where' => " id ='$entryRecord[id]'"));
            } else {
                //新增
                $userNo = codeTemplateClass::generateCode('staffEntryRecord',[
                    'prefix' => 'RZSQ' . date('Ymd'),
                    'table' => 'staff_entry_record',
                    'field' => 'orderNo',
                    'where' => '',
                ],$entryField);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $staffEntryRecordId = self::getId();
                $entryField = array_merge($entryField, [
                    'id' => $staffEntryRecordId,
                    'state' => '草稿',
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'talentId' => $info['id']
                ]);
                $warn = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
                $entryRecord['id'] = $staffEntryRecordId;

            }
            if (!in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = $warn;
                $isPass = false;
            }

            //添加或更新学习经历
            if (is_array($studyIdArr)) {
                foreach ($studyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'study_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'study_history',
                            "field" => [
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        $warn = static::insert([
                            "table" => 'study_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新工作经历
            if (is_array($workIdArr)) {
                foreach ($workIdArr as $k => $nid) {
                    if (static::total(array('table' => 'job_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'job_history',
                            "field" => [
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'job_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新家庭成员
            if (is_array($familyIdArr)) {
                foreach ($familyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'talent_family',
                            "field" => [
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'talent_family',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    $isPass = false;
                }
            }
            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务

                //删除不在此ID中的数据
                delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$id'"));
                delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$id'"));
                delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$id'"));
                $url = root . "control/adIndex.html?cla=staffEntryRecord&fun=detail&id=" . $entryRecord['id'];
                //添加日志
                $text =str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['name'],$id],L('staffProfiles.talentPool.talentEntryLog'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = $url;
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 打印
     */
    public function printPage(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        $staffObj = new staffProfilesClass();
        $age = $staffObj->age($info['birthDay']);
        $exJob = query('job', " id = '$info[jobId]'");
        $workYear = date('y', strtotime($info['workDate']));
        //工作经历
        $result = find(array('table' => 'job_history', 'where' => " talentId = '$info[id]' order by list asc"));
        $workHtml = '';
        $startAndEnd = L('recruitment.table.startAndEnd');
        $station = L('staffProfiles.table.station');
        $work_content = L('staffProfiles.table.work_content');
        $study_major = L('staffProfiles.table.study_major');
        $achievements = L('staffProfiles.table.achievements');
        foreach ($result['array'] as $array) {
            $workHtml .= <<<efo
 <div style="font-size: 15px;height: 30px;line-height: 30px">{$array['companyName']}</div>
    <ul><li><span class="light-color">$startAndEnd</span>：{$array['workDate']}</li></ul>
    <ul><li><span class="light-color">$station</span>：{$array['position']}</li></ul>
    <ul><li><span class="light-color">$work_content</span>：{$array['content']}</li></ul>
efo;

        }

        //教育经历
        $result = find(array('table' => 'study_history', 'where' => " talentId = '$info[id]' order by list asc"));
        $studyHtml = '';
        foreach ($result['array'] as $array) {
            $studyHtml .= <<<efo
 <div style="font-size: 15px;height: 30px;line-height: 30px">{$array['college']}</div>
    <ul><li><span class="light-color">$startAndEnd</span>：{$array['studyDate']}</li></ul>
    <ul><li><span class="light-color">$study_major</span>：{$array['major']}</li></ul>
    <ul><li><span class="light-color">$achievements</span>：{$array['certificate']}</li></ul>
efo;

        }

        $education= L('staffProfiles.table.education');
        $appliedJob = L('staffProfiles.table.appliedJob');
        $work_experience = L('staffProfiles.table.work_experience');
        $edu_experience = L('staffProfiles.table.edu_experience');
        $major = L('staffProfiles.table.major');
        $expect_address=L('staffProfiles.table.expect_address');
        $college=L('staffProfiles.table.college');
        $expect_salary=L('staffProfiles.table.expect_salary');
        $sText=str_replace(['{{age}}','{{workYear}}'],[$age,$workYear],L('staffProfiles.talentPool.printText'));
        $divHtml = <<<efo

<div class="print-content">
<div style="font-weight: bold;font-size: 20px;height: 30px;line-height: 30px">{$info['name']}</div>
    <div class="cv-block">
    <ul><li>{$info['sex']}&emsp;&emsp;$sText&emsp;&emsp;{$info['tel']}</li></ul>
    <ul><li><span class="light-color">$education</span>：{$info['education']}</li><li><span class="light-color">$major</span>：{$info['major']}</li><li><span class="light-color">$college</span>：{$info['college']}</li></ul>
    <ul><li><span class="light-color">$appliedJob</span>：{$exJob['name']}</li><li><span class="light-color">$expect_address</span>：{$info['exWorkPlace']}</li><li><span class="light-color">$expect_salary</span>：{$info['exSalary']}</li></ul>
    </div>
    <div class="cv-block" style="margin-top: 40px">
    <p><h3 style="font-weight: bold">$work_experience</h3></p>
    <div style="border-top: 1px solid #f2f2f2;"></div>
       {$workHtml}
    </div>
    <div class="cv-block" style="margin-top: 40px">
    <p><h3 style="font-weight: bold">$edu_experience</h3></p>
    <div style="border-top: 1px solid #f2f2f2;"></div>
     {$studyHtml}
    </div>
    <div class="cv-block" style="margin-top: 40px">
    
   
</div>
<style>
.print-content{
  font-size: 14px;
}
 .print-content ul{
   margin: 15px 0;
   display: flex;
 }
 .print-content ul li{
   float: left;
   flex: 1;
 }
 .light-color{
 color: grey;
 }
</style>
efo;

        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                        $divHtml
                    </div>

eof;
        $print = new printClass();

        return $print->showPrint($html);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('staffProfiles.talentPool.find_none');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                'menu' => [
                    "detail" => L('staffProfiles.detail.base'),
                    "studyHistory" => L('staffProfiles.detail.social_resume'),
                    "faceRecord" => L('staffProfiles.talentPool.interview'),
                    "record" => array("name" => L('staffProfiles.talentPool.follow'), "cla" => "follow", "fun" => "talentRecord"),
                ]
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                $option = explode('，', para('talentPoolState'));
                $li = '';
                if (is_array($option)) {
                    foreach ($option as $v) {
                        $li .= "<li>$v</li>";
                    }
                }
                //此人才库对应的离职员工
                $quitStaff = query('staff', " talentId = '$info[id]' and state = '离职'");
                if ($info['workFlow'] == 0 || $quitStaff['stid']) {
                    //按钮
                    $button[] = [
                        "name" => L('staffProfiles.button.edit'),
                        "type" => "顶部页卡",
                        "title" => L('staffProfiles.button.edit'),
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('staffProfiles.button.entry'),
                        "type" => "顶部页卡",
                        "title" => "入职申请",
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=entry&id=' . $info['id'],
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('staffProfiles.button.del'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.printResume'),
                    "type" => "点击事件",
                    "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
                ];
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.settingState')."<div class='stateBlock stateBlockDetail' ><ul>{$li}</ul></div>",
                    "type" => "点击事件",
                    "fun" => "showState()",
                ];
            }

            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '人才库');
            //职位
            $job = query('job', " id = '$info[jobId]'");
            $staffObj = new staffProfilesClass();
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('staffProfiles.table.name') => $info['name'],
                        L('staffProfiles.table.sex') => $info['sex'],
                        L('staffProfiles.table.tel') => $info['tel'],
                    ),
                    array(
                        L('staffProfiles.table.email') => $info['email'],
                        L('staffProfiles.table.idCard') => $info['idCard'],
                        L('staffProfiles.table.birthDay')=> $info['birthDay'],

                    ),
                    array(
                        L('staffProfiles.table.age') => $staffObj->age($info['birthDay']),
                        L('staffProfiles.table.nation') => $info['nation'],
                        L('staffProfiles.table.homeTown') => $info['homeTown'],
                    ),
                    array(
                        L('staffProfiles.table.appliedJob') => $job['name'],
                        L('staffProfiles.table.expect_address') => $info['exWorkPlace'],
                        L('staffProfiles.table.expect_salary') => $info['exSalary'],
                    ),
                    array(
                        L('staffProfiles.table.stateText') => $info['state']
                    )

                ),
                L('staffProfiles.detail.info') => array(
                    array(
                        L('staffProfiles.table.education') => $info['education'],
                        L('staffProfiles.table.major') => $info['major'],
                        L('staffProfiles.table.college') => $info['college'],
                    ),
                    array(
                        L('staffProfiles.table.workInDate') => $info['workDate'],
                        L('staffProfiles.table.jobTitle') => $info['jobTitle'],
                    ),
                    array(
                        L('staffProfiles.table.marriage') => $info['marriage'],
                        L('staffProfiles.table.politicsStatus') => $info['politicsStatus'],
                    ),
                    array(
                        L('staffProfiles.table.height') => $info['height'] . 'cm',
                        L('staffProfiles.table.health') => $info['weight'] . 'kg',
                        L('staffProfiles.table.health') => $info['health'],
                    ),
                    array(
                        L('staffProfiles.table.residenceAddress') => $info['residenceAddress'],
                        L('staffProfiles.table.residenceType') => $info['residenceType'],
                    ),
                    array(
                        L('staffProfiles.table.liveAddress') => $info['liveAddress'],
                        L('staffProfiles.table.postCode') => $info['postCode'],
                    ),
                    array(
                        L('staffProfiles.table.secContactName') => $info['secContactName'],
                        L('staffProfiles.table.secContactRelation') => $info['secContactRelation'],
                        L('staffProfiles.table.secContactTel') => $info['secContactTel'],
                    ),
                    array(
                        L('staffProfiles.table.text') => $info['text'],
                    ),
                ),
                L('staffProfiles.table.enclosure') => array(
                    array(
                        $fileCollection
                    ),
                ),
            ));
            $data['html'] .= <<<eof
            <input name="id" type="hidden" value="{$info['id']}">
            <script>
            $(".stateBlock li").click(function (){
                let state = $(this).text();
               let id = $("[name='id']").val();
                showState();
                subForm('form',root+'control/adIndex.html?cla=talentPool&fun=setWorkFlow&state='+state+'&id='+id)
            });
            </script>
eof;

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function faceRecord()
    {
        $edit = $del = '';
        $id = $this->get('id');
        $checkAll = $this->checkAll("faceForm", "faceId");
        $tr[] = array($checkAll,
            L('staffProfiles.talentPool.intervier'),
            L('staffProfiles.talentPool.interviewDept'),
            L('staffProfiles.talentPool.interviewDate'),
            L('staffProfiles.detail.assessment'),
            L('staffProfiles.talentPool.evaluation'),
            L('staffProfiles.talentPool.opinion'));
        $sql = find(array("table" => "talent_pool_interview", "where" => " talentId = '" . $id . "' order by time desc "));
        $url = root . "control/adIndex.html?cla=" . self::page . "";
        foreach ($sql['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "faceId", "value" => $array['id']),
                "edit" => array("title" => L('staffProfiles.table.talentInfo'), "click" => "newIframe('" . L('staffProfiles.table.talentInfo') . "','" . $url . "&fun=info&talentId={$array['talentId']}&id=" . $array['id'] . "')"),
                "detail" => array("title" =>L('staffProfiles.table.talentInfo'), "click" => "newIframe('" . L('staffProfiles.table.talentInfo') . "','" . $url . "&fun=infoDetail&talentId={$array['talentId']}&id=" . $array['id'] . "')"),
            );
            $itemMx = find(array('table' => 'talent_pool_interview_detail', 'single' => "orderId = '$array[id]' group by orderId", 'field' => "group_concat(concat(itemName,'：',score) separator '<br>') as name"));
            $tr[] = array($this->dominate($dominate), self::findStaff($array['managerId']), $array['managerDept'], $array['recordDate'], $itemMx['name'] ?? '', $array['evaluation'], $array['opinion']);
        }
        if ($this->power(self::page, "interviewEdit")) {
            $edit = "<span class='spanButton'  onclick=\"newIframe('" .L('staffProfiles.table.talentInfo'). "','" . $url . "&fun=info&talentId={$id}')\">".L('staffProfiles.button.addNew')."</span>\n";
        }
        if ($this->power(self::page, "interviewDel")) {
            $del = "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delInterview'})\">".L('staffProfiles.button.del')."</span>\n";
        }
        $json['html'] = $edit . $del . space . "<form name='faceForm'>" . $this->tableMany(array("tr" => $tr)) . $this->editJs() . "</form>";
        return json_encode($json, 320);
    }

    /*详情页*/
    public function infoDetail(): string
    {
        $info = query('talent_pool_interview', " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('staffProfiles.talentPool.no_interview_record');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "interviewEdit")) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.edit'),
                    "type" => "顶部页卡",
                    "title" => L('staffProfiles.button.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=info&talentId=' . $info['talentId'] . '&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "interviewDel")) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'delInterview', "id" => $info['id']],
                ];
            }

            $result = find(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[] = [L('job.model.projectName'),
                L('job.model.projectText'),
                L('job.model.evaluate_item'),
                L('job.model.percent'),
                L('staffProfiles.detail.score')];
            $totalScore = 0;
            foreach ($result['array'] as $array) {
                $mx = query('job_model_detail', "id = '$array[modelId]'");
                $tr[] = [
                    $mx['name'],
                    $mx['text'],
                    $array['itemName'],
                    ($mx['proportion'] * 100) . '%',
                    "<span class='score'>{$array['score']}</span>",
                ];
                $array['score'] = $array['score'] ?: 0;
                $totalScore += $array['score']*$mx['proportion'];
            }
            $tr[] = [L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
            $talent = query(self::table, "id = '$info[talentId]'");
            $job = query('job', "id = '$talent[jobId]'");
            $staffObj = new staffProfilesClass();
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                L('staffProfiles.talentPool.intervierInfo') => array(
                    array(
                        L('staffProfiles.table.name') => $talent['name'],
                        L('staffProfiles.table.sex') => $talent['sex'],
                        L('staffProfiles.table.age') => $staffObj->age($talent['birthDay']),
                    ),
                    array(
                        L('staffProfiles.table.college') => $talent['college'],
                        L('staffProfiles.table.major') => $talent['major'],
                        L('staffProfiles.table.education') => $talent['education'],
                    ),
                    array(
                        L('staffProfiles.table.appliedJob') => departmentClass::getTypeName($job['departmentId']) . '->' . $job['name'],
                        L('staffProfiles.table.expect_address') => $talent['exWorkPlace'],
                        L('staffProfiles.table.expect_salary') => $talent['exSalary']
                    ),
                ),
                L('staffProfiles.talentPool.interviewMaInfo') => array(
                    array(
                        L('staffProfiles.talentPool.interviewDate') => $info['recordDate'],
                        L('staffProfiles.talentPool.interviewMa') => self::findStaff($info['managerId']),
                    ),
                ),
                L('staffProfiles.detail.assessment') => array(
                    array(
                        $this->tableMany(array('tr' => $tr))
                    )
                ),
                L('staffProfiles.talentPool.evaluation')  => array(
                    array(
                        L('staffProfiles.detail.all_evaluation') => $info['evaluation']
                    ),
                    array(
                        L('staffProfiles.talentPool.opinion') => $info['opinion'],
                        L('staffProfiles.talentPool.interviewState') => $info['workFlow']
                    )
                ),
                L('staffProfiles.table.enclosure') => array(
                    array(
                        fileUploadClass::showFile($info['id'])
                    )
                )
            ));

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function info()
    {
        $id = $this->get('id') ?: suiji();
        $talentId = $this->get('talentId');
        $info = query('talent_pool_interview', " id = '" . $id . "' ");
        $talent = query(self::table, "id = '$talentId'");
        //按钮
        $button[] = [
            "name" => L('staffProfiles.table.save'),
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "InfoForm',root+'control/adIndex.html?cla=" . self::page . "&fun=infoEdit')",
            "post" => ["id" => $id],
            'style' => 'li-btn-blue-bg',
        ];
        $job = query('job', "id = '$talent[jobId]'");
        //能力评定
        $tr[] = [L('job.model.projectName'),
            L('job.model.projectText'),
            L('job.model.evaluate_item'),
            L('job.model.percent'),
            L('staffProfiles.detail.score')];
        $all = find(array('table' => 'job_model_detail', 'where' => "jobId = '$talent[jobId]' order by time asc"));
        $totalScore = 0;
        foreach ($all['array'] as $array) {
            $mx = query('talent_pool_interview_detail', "orderId = '$info[id]' and modelId = '$array[id]'");
            $tr[] = [
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name'=>'proportion[]','value'=>$array['proportion'])).
                $array['name'],
                $array['text'],
                repeatSelect(array('name' => 'itemName[]', 'change' => 'getScore', 'sqlField' => 'name', 'sqlForm' => "job_model_item where orderId = '$array[id]' order by any_value(list)", 'title' => '请选择', 'value' => $mx['itemName'])),
                ($array['proportion'] * 100) . '%',
                "<span class='score'>{$mx['score']}</span>",
            ];
            $mx['score'] = $mx['score'] ?: 0;
            $totalScore += $mx['score']*$array['proportion'];
        }
        $tr[] = [L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
        $faceWorkFlow = explode('，', para('talentPoolState'));
        $staffObj = new staffProfilesClass();
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.talentPool.intervierInfo')."</span>"
                ],
                [
                    L('staffProfiles.table.name')."：" => $talent['name'],
                    L('staffProfiles.table.sex')."：" => $talent['sex'],
                    L('staffProfiles.table.age').'：' => $staffObj->age($talent['birthDay']),
                ],
                [
                    L('staffProfiles.table.college')."：" => $talent['college'],
                    L('staffProfiles.table.major')."：" => $talent['major'],
                    L('staffProfiles.table.education')."：" => $talent['education'],
                ],
                [
                    L('staffProfiles.table.appliedJob')."：" => departmentClass::getTypeName($job['departmentId']) . '->' . $job['name'],
                    L('staffProfiles.table.expect_address').'：' => $talent['exWorkPlace'],
                    L('staffProfiles.table.expect_salary').'：' => $talent['exSalary']
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.talentPool.interviewMaInfo')."</span>"
                ],
                [
                    must . L('staffProfiles.talentPool.interviewDate')."：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . L('staffProfiles.talentPool.interviewMa')."：" => selectMultiple(array('name' => 'managerId', 'value' => $info['managerId'] ?: self::$stid, 'title' => '请选择', 'sqlId' => 'stid', 'sqlField' => 'name', 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc")),
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.detail.assessment')."</span>"
                ],
                [
                    $this->tableMany(array('tr' => $tr))
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.talentPool.evaluation')."</span>"
                ],
                [
                    must . L('staffProfiles.detail.all_evaluation')."：" => textarea(array('name' => 'evaluation', 'class' => 'textarea', 'value' => $info['evaluation']))
                ],
                [
                    must . L('staffProfiles.talentPool.opinion')."：" => radio(array('name' => 'opinion', 'checked' => $info['opinion'] ?: $this->opinionOption[0], 'value' => $this->opinionOption)),
                    must . L('staffProfiles.talentPool.interviewState')."：" => radio(array('name' => 'workFlow', 'checked' => $info['workFlow'] ?: $faceWorkFlow[0], 'value' => $faceWorkFlow))
                ],
                [
                    "<span class='small-title'>".L('staffProfiles.table.enclosure')."</span>"
                ],
                [
                    fileUploadClass::addFileComponent($info['id'], '面试记录', self::page, self::page . 'InfoForm'),
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'talentId', 'value' => $this->get('talentId'))),
            'button' => ' '
        ]);
        //返回
        $data['html'] .= <<<eof
<script>
function getScore(e) {
  let val = e.value;
  let modelId = $(e).parent().parent().find("[name='detailId[]']").val();
  $.post(root+'control/adIndex.html?cla=talentPool&fun=getScore',{name:val,modelId:modelId},function(res) {
      $(e).parent().parent().find(".score").html(res.data.score);
      $(e).parent().parent().find("[name='proportion[]']").val(res.data.rate);
      addScore();
  },'json')
}
function addScore(){
    let num = 0;
    let proportion = 0;
    $(".score").each(function() {
        proportion = Number($(this).parent().parent().find("[name='proportion[]']").val())
       num+=Number($(this).html())*proportion;
    })
    $("#totalScore").html(num.toFixed(1));
}
</script>
eof;

        return $this->tab($data);
    }

    public function infoEdit()
    {

        $id = $this->post('id');
        $info = query('talent_pool_interview', " id = '$id'");
        $talentPool = query(self::table, "id = '" . $this->post('talentId') . "'");
        $field = [
            'recordDate' => $this->post('recordDate'),
            'managerId' => $this->post('managerId'),
            'evaluation' => $this->post('evaluation'),
            'opinion' => $this->post('opinion'),
            'workFlow' => $this->post('workFlow')

        ];
        $annotation = [
            'recordDate' => L('staffProfiles.talentPool.interviewDate'),
            'managerId' => L('staffProfiles.talentPool.interviewMa'),
            'evaluation' => L('staffProfiles.talentPool.all_evaluation'),
            'opinion' => L('staffProfiles.talentPool.opinion'),
            'workFlow' => L('staffProfiles.talentPool.interviewState'),
        ];
        $rules = [
            'recordDate' => 'required|date',
            'managerId' => 'required',
            'evaluation' => 'required',
            'opinion' => 'required',
            'workFlow' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $detailIdArr = $this->post('detailId') ?? [];
        $itemNameArr = $this->post('itemName');
        //附件
        $fileIdArr = $this->post('fileId');
        //判断
        if (!$this->power(self::page, "interviewEdit")) {
            $json['warn'] = L('staffProfiles.talentPool.interviewEditPer');
        } elseif (empty($talentPool['id'])) {
            $json['warn'] = L('staffProfiles.talentPool.find_none');
        } elseif (static::is_null_array($detailIdArr)) {
            $json['warn'] =  L('staffProfiles.tip.find_none_item');
        } elseif (static::is_null_array($itemNameArr)) {
            $json['warn'] =  L('staffProfiles.tip.evaluate_warn');
        } else {
            $this->startTrans();//开启事务
            if (empty($info['id'])) {
                $manager = query('staff', "stid = '$field[managerId]'");
                $job = query('job', "id = '$manager[jobId]'");
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => self::$stid,
                    'talentId' => $talentPool['id'],
                    'managerDept' => departmentClass::getTypeName($job['departmentId'])
                ]);
                $json['warn'] = static::insert(array('table' => 'talent_pool_interview', 'field' => $field));
            } else {
                $json['warn'] = static::update(array(
                    'table' => 'talent_pool_interview',
                    'field' => $field,
                    'where' => "id = '$info[id]'"
                ));
            }
            delete(array('table' => 'talent_pool_interview_detail', 'where' => " orderId = '$id'"));
            foreach ($detailIdArr as $k => $val) {
                $job_model_item = query('job_model_item', "orderId = '" . $val . "' and name = '" . $itemNameArr[$k] . "'");
                $bool = static::insert(array('table' => 'talent_pool_interview_detail',
                    'field' => [
                        'id' => suiji(),
                        'orderId' => $id,
                        'modelId' => $val,
                        'itemName' => $itemNameArr[$k],
                        'score' => $job_model_item['score'],
                    ]));
                if ($bool != '新增成功') {
                    $json['warn'] = L('staffProfiles.tip.editFailed');
                    break;
                }
            }
            //更新人才库状态
            $bool = update(array('table' => self::table, 'field' => ['state' => $field['workFlow']], 'where' => "id = '$talentPool[id]'"));
            if ($bool != '更新成功') {
                $json['warn'] =L('staffProfiles.talentPool.updateState');
            }
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $bool = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($bool != '更新成功') {
                    $json['warn'] = $bool;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$talentPool['name'],$id],L('staffProfiles.talentPool.interviewLog'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=faceRecord&id=" . $talentPool['id'];
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    public function getScore()
    {
        $model = query('job_model_detail',"id = '" . $this->post('modelId') . "'");
        $info = query('job_model_item', "orderId = '" . $this->post('modelId') . "' and name = '" . $this->post('name') . "'");
        $json['data']['rate'] = $model['proportion'];
        $json['data']['score'] = $info['score'];
        return json_encode($json, 320);
    }

    /**
     * 学习经历
     * @return bool|string
     */
    public function studyHistory()
    {
        $id = $this->get('id');
        $staff = query('staff', "stid = '" . $id . "'");
        if (!empty($staff['stid'])) {
            $id = $staff['talentId'];
        }
        if (!$this->power(self::page, "see")) {
            $json['html'] =L('staffProfiles.talentPool.see_permission');
        } else {
            $tr[] = [L('staffProfiles.table.study_date'),
                L('staffProfiles.table.university'),
                L('staffProfiles.table.study_major'),
                L('staffProfiles.table.achievements')];
            $sql = find(array("table" => "study_history", "where" => " talentId = '" . $id . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $tr[] = array($array['studyDate'], $array['college'], $array['major'], $array['certificate']);
            }

            $wrokTr[] = [L('staffProfiles.table.work_date_start'),
                L('staffProfiles.table.employed'),
                L('staffProfiles.table.station'),
                L('staffProfiles.table.work_content'),
                L('staffProfiles.table.quit_reason')];
            $sql = find(array("table" => "job_history", "where" => " talentId = '" . $id . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $wrokTr[] = array($array['workDate'], $array['companyName'], $array['position'], $array['content'], $array['cause']);
            }

            $faTr[] = [L('staffProfiles.table.name'),
                L('staffProfiles.table.relationship'),
                L('staffProfiles.table.work_unit'),
                L('staffProfiles.table.contactTel')];
            $sql = find(array("table" => "talent_family", "where" => " talentId = '" . $id . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $faTr[] = array($array['name'], $array['relation'], $array['company'], $array['contactTel']);
            }
            //构建表单
            $json['html'] = space . "<div class='layerList' style='margin-left: 0'><span class='small-title'>学习经历</span>" . $this->tableMany(array("tr" => $tr)) . space . "<span class='small-title'>工作经历</span>" . $this->tableMany(array("tr" => $wrokTr)) . space . "<span class='small-title'>家庭成员</span>" . $this->tableMany(array("tr" => $faTr)) . "</div>";
        }
        //返回
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delInterview':
                $act = 'del';
                $msg = L('staffProfiles.talentPool.delTalentPool');
                $title = self::page . 'DelInterview';
                $function = 'delInterview';
                $form = self::page . 'OperateForm, faceForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg =  L('staffProfiles.talentPool.delTalentPool');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'],[$msg],L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    public function delInterview()
    {
        $array = $this->post('faceId') ?: $this->post('id');
        if (!$this->power(self::page, "interviewDel")) {
            $json['warn'] = L('staffProfiles.talentPool.interviewDelPer');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query('talent_pool_interview', " id = '$id' ");
                delete(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$id'"));
                $all = find(array('table' => "file", "where" => "targetId = '$id'"));
                foreach ($all['array'] as $val) {
                    fileDelete($val['src']);
                }
                //删除附件
                delete(array("table" => 'file', "where" => " targetId = '$id' "));
                //最后删除基本参数
                delete(array("table" => 'talent_pool_interview', "where" => " id = '$id' "));
                //返回
                $warn = L('job.other.delete_success');
                $x++;
                $text .= L('staffProfiles.talentPool.interview')."【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('staffProfiles.talentPool.delInterview'))."<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] =str_replace(['{{x}}'],[$x],L('staffProfiles.talentPool.delInterviewLog'));
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=faceRecord&id=" . ($info['talentId'] ?? '');
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] =  L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $force = staffProfilesClass::forceDel();
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (!$force && $info['workFlow']) {
                    $warn = L('staffProfiles.talentPool.delTalentError');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除工作经历
                    delete(array("table" => 'job_history', "where" => " talentId = '$id' "));
                    //删除学习经历
                    delete(array("table" => 'study_history', "where" => " talentId = '$id' "));
                    //删除家庭成员
                    delete(array("table" => 'talent_family', "where" => " talentId = '$id' "));
                    $all = find(array('table' => "file", "where" => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                    }
                    //删除附件
                    delete(array("table" => 'file', "where" => " targetId = '$id' "));
                    //删除面试记录
                    delete(array("table" => 'talent_pool_interview_detail', "where" => " orderId in (select id from talent_pool_interview where talentId = '$id') "));
                    //删除面试记录
                    delete(array("table" => 'talent_pool_interview', "where" => " talentId = '$id' "));
                    delete(array("table" => 'staff_entry_record', "where" => " talentId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));

                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }
                $text .= str_replace(['{{name}}','{{id}}'],[$info['name'],$info['id']],L('staffProfiles.talentPool.delTalentTextA')). $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('staffProfiles.talentPool.delTalentText')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('staffProfiles.talentPool.delTalentTextLog'));
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        return json_encode($json, 320);
    }
}

